<!--
*@Author: QWP
*@Description: 车辆维修保养申请弹窗
*@Date 2024-09-18 12:51
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :hideBtns="state.isCheck || isReport ? ['confirm'] : []"
    :confirmLoading="state.formLoading"
    @submit="submit"
    @close="dialogClose">
    <u-busi-card title="维保信息">
      <u-form
        ref="formRef"
        :elements="state.elements"
        :model="state.form"
        :disabled="state.isCheck || isReport">
      </u-form>
    </u-busi-card>
    <u-busi-card title="附件信息">
      <u-form
        ref="form3"
        :elements="state.fileEls"
        :model="state.fielForm"
        :disabled="isReport"
      ></u-form>
    </u-busi-card>
  </u-dialog>
</template>
<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useRoute, useRouter } from "vue-router";
import { useBaseStore, useLoginStore } from '@/store'
import { storeToRefs } from "pinia";
import { alertC, confirmC, nullC, numberC, isValue, jsonCopy, messageC } from '@/util/common';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import * as checkApi from '@/service/administration/yearCheck'
import * as insureApi from '@/service/administration/carInsure'
import * as driverApi from '@/service/administration/driver'

const props = defineProps<{
  keyid: string,
}>()

const attrs = useAttrs()
const route = useRoute()
const emits = defineEmits(['success'])

// 是否是报表
const isReport = computed(() => route.params.pType == 2)

const { userInfo } = storeToRefs(useLoginStore())
const { deptUsers, PAYFEE_TYPE } = storeToRefs(useBaseStore())

const formItemProps = {
  labelWidth: '140px',
  colon: false
}

const formRef = ref()
const baseData = ref<{ [key: string]: [] }>({
  bxgsData: [], // 保险公司数据
  lxrdata: [], // 联系人数据
  cpdata: [], // 车辆 信息
})

// 实际收款人
const filterLxrData = computed(() => {
  // 支付方式为公务卡，这选择本部门下的人
  // 支付方式为转账、现金则选择机构下的人员
  if(['1', '2'].includes(state.form.paytype + '')) {
    return cloneDeep(baseData.value.lxrdata).filter((item) => item.keyid == state.form.fkactmechanismid)
  }
  else if(state.form.paytype == 3) {
    let deptInfo = deptUsers.value.find(i => i.keyid == userInfo.value.deptId) || {};
    return deptInfo['children'] || []
  }
  return []
})

const state = reactive({
  form: {
    fkvehicleid: "",
    vehiclenumber: "",
    vehicleadminname: "",
    applicantphone: nullC(userInfo.value['tel']),
    applicantid: "",
    applicantname: "",
    fkusername: '', 
    applicationdate: "",
    applicationtype: '',
    // applicationtype:3,
    inspectionplandate: "",
    plandays: "",
    fkmechanismid: "",
    fkmechanismname: "",
    inspectionreason: "",
    ssdeptname: "",
    ssdeptid: "",
    status: "",
  
    actualcomdate:'',
    balanceamt:"",
    curmeliage:'',
    fkactmechanismid:'',
    fkactmechanismname:'',
    paytype:'',
    actualpayee:'',
    remark:'',
  },
 
  elements: [
    { label: '车牌号', key: 'fkvehicleid', col: { span: 8,}, element: 'select', 
      formItemProps: { ...formItemProps,  required: true,},
      componentProps: {
        options: computed(() => baseData.value.cpdata),
        fieldNames: { label: 'platenumber', value: 'keyid' },
        onChange: (val) => {
          getAddData(val)
        }
      }
    },
    { label: '车辆所属部门', key: 'ssdeptname', col: { span: 8,}, element: 'input', 
      formItemProps: { ...formItemProps,  required: true,},
      componentProps: {
        disabled: true
      }
    },
    { label: '申请人', key: 'applicantid', col: { span:8,}, element: 'selUserTree', 
      formItemProps: { ...formItemProps, },
      componentProps: {
        disabled: true,
        multiple: false,
        class: 'f-normal-disable ',
        fieldNames: { label: 'name', value: 'keyid' },
        onChange: (e) => {
          let tE = (e || []).length == 0 ? {} : e[0]
          state.form.applicantname = nullC(tE['name'])
        }
      }
    },
    { label: '申请时间', key: 'applicationdate', col: { span: 8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps,  required: true,},
      componentProps: {
        disabled: true,
      }
    },
    { label: '申请人电话', key: 'applicantphone', col: { span: 8,}, element: 'input', 
      formItemProps: { ...formItemProps, },
      componentProps: {
      }
    },
    { label: '申请类型', key: 'applicationtype', col: { span: 8,}, element: 'select', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: [{label:'维修',value:1},{label:'保养',value:2}]
      }
    },
    { label: '维修保养事项', key: 'inspectionreason', col: { span: 24,}, element: 'textarea', 
      formItemProps: { ...formItemProps, required: true,},
      componentProps: {
        maxlength: 200, showCount: true
      }
    },
    { label: '维修保养完成时间', key: 'actualcomdate', col: { span: 8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps,  required: true},
      componentProps: {
        disabledDate:(current: Dayjs) =>{
          return current && current > dayjs().endOf('day')
        }
      }
    },
    { label: '维修保养车辆里程', key: 'curmeliage', col: { span: 8,}, element: 'number', 
      formItemProps: { ...formItemProps,  required: true},
      componentProps: {
        controls: false, min: 0, precision: 0, addonAfter: 'KM'
      }
    },
    { label: '结算费用(元)', key: 'balanceamt', col: { span: 8,}, element: 'money', 
      formItemProps: { ...formItemProps,  required: false},
      componentProps: {
        addonAfter: '元'
      }
    },
    { label: '实际维修保养机构', key: 'fkactmechanismid', col: { span: 8,}, element: 'select', 
      formItemProps: { ...formItemProps,  required: true},
      componentProps: {
        options: computed(() => baseData.value.bxgsData),
        fieldNames: { label: 'mechanismname', value: 'keyid' } ,
        onChange: function(val, o){
          state.form.fkactmechanismname = baseData.value.bxgsData.find((item) => item.keyid == val).mechanismname;
          state.form.actualpayee = ''
        }
      }
    },
    { label: '支付方式', key: 'paytype', col: { span: 0,}, element: 'select', 
      formItemProps: { ...formItemProps,  required: false},
      componentProps: {
        options: PAYFEE_TYPE.value,
        onChange: (val) => {
          state.form.actualpayee = '';
        }
      }
    },
    { label: '实际收款人', key: 'actualpayee', col: { span: 0,}, element: 'select', 
      formItemProps: { ...formItemProps,  required: false},
      componentProps: {
        options: filterLxrData,
        fieldNames: { label: 'name', value: 'keyid' }
      }
    },
    { label: '备注', key: 'remark', col: { span: 24,}, element: 'textarea', 
      formItemProps: { ...formItemProps,  required: false},
      componentProps: {
        maxlength: 200, showCount: true
      }
    },
  ],

  fielForm: {},
  fileEls: [
    { label: '', key: 'appendixSaveVOList', col: { span: 24,}, element: 'file', 
      formItemProps: { ...formItemProps, },
      componentProps: {
        fileParams: {
          biztype: '3',
          bucket: 'VEHICLE_BIZ_TYPE_INSPECTION',
          moduletype:'VEHICLE'
        }
      }
    },
  ],

  formLoading: false,
  
})

// 保存
async function submit() {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    messageC("请先将表单信息填写完毕！");
    return
  }

  const url = state.form.keyid ? 'update' : 'add';
  if(url == 'add') {
    state.form.status = '1'
  }

  state.formLoading = true;
  try {
    const res = await checkApi[url]({ ...state.form, ...state.fielForm })
    if (res.code == 0) {
      messageC(res.msg, 'success');
      emits('success');
      dialogClose()
    } else {
      messageC(res.data.msg, 'error');
    }
  } catch (error) {}
  state.formLoading = false;
}

// 初始化信息
function initFormInfo() {
  state.form.fkuserid = userInfo.value['userId']
  state.form.fkusername = userInfo.value['name']
  state.form.fkdeptid = userInfo.value['deptId']
  state.form.redeptname = userInfo.value['deptName']
  state.form.fkunitsid = userInfo.value['unitId']

  state.form.applicantid = userInfo.value['userId']
  state.form.applicantname = userInfo.value['name']
  state.form.applicantphone = userInfo.value['tel']
  state.form.applicationdate = dayjs().format('YYYY-MM-DD')
}

// 选择车牌号获取回显信息
function getAddData(val) {
  let carInfo = baseData.value.cpdata.find((item) => item.keyid == val) || {};
  state.form.vehiclenumber = nullC(carInfo['platenumber'])
  state.form.ssdeptname = nullC(carInfo['ssdeptname'])
  state.form.ssdeptid = nullC(carInfo['ssdeptid'])
}

// 获取枚举
async function getEnmu() {
  getOrgnizition();
  getCarNum();
  getlxUser();
}

// 获取车辆信息
async function getCarNum() {
  try {
    const res = await driverApi.selectPlateNumber()
    if (res.code == 0) {
      baseData.value.cpdata = res.data || []
    }
  } catch (error) {}
}

// 获取维修机构
async function getOrgnizition() {
  try {
    const res = await insureApi.to_add1();
    if(res.code == 0) {
      // 维修机构
      if (res.data.wxMechanismList) {
        baseData.value.bxgsData = (res.data.wxMechanismList || [])
      }
    }
  } catch (error) {}
}

// 获取机构联系人
function getlxUser() {
  checkApi.linkUser().then((res) => {
    if (res.data.code == 0) {
      let tData = res.data.data.mechanismList || []
      baseData.value.lxrdata = tData.map(i => {
        return { ...i, name: i['mechanismname'] }
      })
    }
  });
}

// 回显
async function getHxData() {
  state.formLoading = true;
  try {
    const res = await checkApi.updateQuery(props.keyid)
    if (res.code == 0) {
      state.form = res.data.vtInspection || {};
      state.form.vehicleadminname = state.form.fkusername;

      // 附件信息
      state.fielForm.appendixSaveVOList = res.data.inspectionattaches || []
    }
  } catch (error) {}
  state.formLoading = false;
}

// 弹窗关闭
function dialogClose() {
  for (let key in state.form) {
    if(key == 'applicantphone') {
      state.form.applicantphone = nullC(userInfo.value['tel'])
    } else {
      state.form[key] = '';
    }
  }
  formRef.value.form.resetFields()
  
  for (let key in state.fielForm) {
    state.fielForm[key] = '';
  }
}

watch(() => attrs.open, (nval, oval) => {
  if(nval == true) {
    initFormInfo();
    getEnmu();
    if (props.keyid) {
      state.form.keyid = props.keyid;
      getHxData();
    }
  }
})
</script>
<style lang="scss">
.u-yeay-check-edit-dialog {
  .show-none {
    display: none;
  }
}
</style>
